import React, { useState, useEffect } from 'react';
import { Card, Table, Button, message, Tag, Space, Breadcrumb, Row, Col, Modal, Select, Tooltip, Input, Checkbox, Divider, Progress, Alert } from 'antd';
import { ArrowLeftOutlined, EyeOutlined, PlusOutlined, DeleteOutlined, ScanOutlined, InfoCircleOutlined, SearchOutlined, FilterOutlined, IdcardOutlined, CodeOutlined, ApiOutlined, BranchesOutlined, DownloadOutlined, PlayCircleOutlined, CloseCircleOutlined } from '@ant-design/icons';
import * as XLSX from 'xlsx';
import { useParams, useNavigate } from 'react-router-dom';
import {
    getApplication,
    getApplicationUnits,
    type ApplicationData,
    type UnitMetricsData
} from '../../services/metrics';
import { manualTriggerScan, getUnit, triggerBatchScan, getBatchScanProgress, cancelBatchScan, getBatchScanHistory } from '../../services/unit';

const { Option } = Select;

// 单元信息Tooltip组件
const UnitInfoTooltip: React.FC<{ unitId: string }> = ({ unitId }) => {
    const navigate = useNavigate();
    const [unitConfig, setUnitConfig] = useState<any>(null);
    const [loading, setLoading] = useState(false);
    const [visible, setVisible] = useState(false);

    const fetchUnitConfig = async () => {
        if (unitConfig || loading) return; // 避免重复加载

        setLoading(true);
        try {
            const response = await getUnit(unitId);
            if (response.code === 0) {
                setUnitConfig(response.data);
            }
        } catch (error) {
            console.error('获取单元配置失败:', error);
        } finally {
            setLoading(false);
        }
    };

    const handleVisibleChange = (visible: boolean) => {
        setVisible(visible);
        if (visible) {
            fetchUnitConfig();
        }
    };

    const handleViewUnit = () => {
        navigate(`/unit/${unitId}`);
    };

    const tooltipContent = loading ? (
        <div style={{ padding: '12px', textAlign: 'center', color: '#666' }}>
            <span>加载中...</span>
        </div>
    ) : unitConfig ? (
        <div style={{ maxWidth: '480px', padding: '4px' }}>
            {/* 标题 */}
            <div style={{
                marginBottom: '12px',
                paddingBottom: '8px',
                borderBottom: '1px solid #e8e8e8',
                display: 'flex',
                alignItems: 'center',
                gap: '6px'
            }}>
                <InfoCircleOutlined style={{ color: '#1890ff', fontSize: '14px' }} />
                <span style={{ fontWeight: '600', fontSize: '14px', color: '#262626' }}>
                    单元配置信息
                </span>
            </div>

            {/* 基本信息区 */}
            <div style={{ marginBottom: '12px' }}>
                <div style={{
                    fontSize: '11px',
                    color: '#8c8c8c',
                    marginBottom: '6px',
                    fontWeight: '500',
                    textTransform: 'uppercase',
                    letterSpacing: '0.5px'
                }}>
                    基本信息
                </div>
                <div style={{
                    background: '#fafafa',
                    padding: '8px 12px',
                    borderRadius: '4px',
                    fontSize: '12px',
                    lineHeight: '1.8'
                }}>
                    <div style={{ display: 'flex', marginBottom: '4px' }}>
                        <span style={{ color: '#8c8c8c', minWidth: '70px', flexShrink: 0 }}>单元ID</span>
                        <span style={{ color: '#262626', fontWeight: '500', flex: 1 }}>{unitConfig.unitId || '-'}</span>
                    </div>
                    <div style={{ display: 'flex', marginBottom: '4px' }}>
                        <span style={{ color: '#8c8c8c', minWidth: '70px', flexShrink: 0 }}>应用ID</span>
                        <span style={{ color: '#262626' }}>{unitConfig.appId || '-'}</span>
                    </div>
                    <div style={{ display: 'flex', marginBottom: '4px' }}>
                        <span style={{ color: '#8c8c8c', minWidth: '70px', flexShrink: 0 }}>单元类型</span>
                        <span style={{ color: '#262626' }}>{unitConfig.unitType || '-'}</span>
                    </div>
                    <div style={{ display: 'flex' }}>
                        <span style={{ color: '#8c8c8c', minWidth: '70px', flexShrink: 0 }}>归属团队</span>
                        <span style={{ color: '#262626' }}>{unitConfig.ownTeam || '-'}</span>
                    </div>
                </div>
            </div>

            {/* Git仓库信息区 */}
            <div style={{ marginBottom: '12px' }}>
                <div style={{
                    fontSize: '11px',
                    color: '#8c8c8c',
                    marginBottom: '6px',
                    fontWeight: '500',
                    textTransform: 'uppercase',
                    letterSpacing: '0.5px'
                }}>
                    Git仓库
                </div>
                <div style={{
                    background: '#fafafa',
                    padding: '8px 12px',
                    borderRadius: '4px',
                    fontSize: '12px',
                    lineHeight: '1.8'
                }}>
                    <div style={{ marginBottom: '6px' }}>
                        <div style={{ color: '#8c8c8c', marginBottom: '2px' }}>仓库地址</div>
                        <div style={{
                            color: '#1890ff',
                            wordBreak: 'break-all',
                            fontSize: '11px',
                            fontFamily: 'Monaco, Consolas, monospace'
                        }}>
                            {unitConfig.gitRepoUrl || '未配置'}
                        </div>
                    </div>
                    <div style={{ display: 'flex', marginBottom: '4px' }}>
                        <span style={{ color: '#8c8c8c', minWidth: '70px', flexShrink: 0 }}>默认分支</span>
                        <Tag color="blue" style={{ margin: 0, fontSize: '11px' }}>
                            {unitConfig.defaultBranch || '-'}
                        </Tag>
                    </div>
                    <div style={{ display: 'flex' }}>
                        <span style={{ color: '#8c8c8c', minWidth: '70px', flexShrink: 0 }}>当前分支</span>
                        <Tag color="green" style={{ margin: 0, fontSize: '11px' }}>
                            {unitConfig.currentBranch || '-'}
                        </Tag>
                    </div>
                </div>
            </div>

            {/* 路径信息区 */}
            <div style={{ marginBottom: unitConfig.branches && unitConfig.branches.length > 0 ? '12px' : '0' }}>
                <div style={{
                    fontSize: '11px',
                    color: '#8c8c8c',
                    marginBottom: '6px',
                    fontWeight: '500',
                    textTransform: 'uppercase',
                    letterSpacing: '0.5px'
                }}>
                    路径配置
                </div>
                <div style={{
                    background: '#fafafa',
                    padding: '8px 12px',
                    borderRadius: '4px',
                    fontSize: '12px',
                    lineHeight: '1.8'
                }}>
                    <div style={{ marginBottom: '6px' }}>
                        <div style={{ color: '#8c8c8c', marginBottom: '2px' }}>代码路径</div>
                        <div style={{
                            color: '#262626',
                            wordBreak: 'break-all',
                            fontSize: '11px',
                            fontFamily: 'Monaco, Consolas, monospace'
                        }}>
                            {unitConfig.codeLocation || '-'}
                        </div>
                    </div>
                    <div>
                        <div style={{ color: '#8c8c8c', marginBottom: '2px' }}>制品路径</div>
                        <div style={{
                            color: '#262626',
                            wordBreak: 'break-all',
                            fontSize: '11px',
                            fontFamily: 'Monaco, Consolas, monospace'
                        }}>
                            {unitConfig.artifactoryPath || '-'}
                        </div>
                    </div>
                </div>
            </div>

            {/* 分支列表区 */}
            {unitConfig.branches && unitConfig.branches.length > 0 && (
                <div>
                    <div style={{
                        fontSize: '11px',
                        color: '#8c8c8c',
                        marginBottom: '6px',
                        fontWeight: '500',
                        textTransform: 'uppercase',
                        letterSpacing: '0.5px'
                    }}>
                        所有分支 ({unitConfig.branches.length})
                    </div>
                    <div style={{
                        background: '#fafafa',
                        padding: '8px 12px',
                        borderRadius: '4px',
                        maxHeight: '120px',
                        overflowY: 'auto'
                    }}>
                        {unitConfig.branches.map((branch: string, index: number) => (
                            <Tag
                                key={index}
                                style={{
                                    marginBottom: '4px',
                                    marginRight: '4px',
                                    fontSize: '11px'
                                }}
                                color={branch === unitConfig.currentBranch ? 'blue' : 'default'}
                            >
                                {branch}
                            </Tag>
                        ))}
                    </div>
                </div>
            )}
        </div>
    ) : (
        <div style={{ padding: '12px', textAlign: 'center', color: '#999' }}>
            <span>暂无数据</span>
        </div>
    );

    return (
        <Tooltip
            title={tooltipContent}
            placement="right"
            overlayStyle={{ maxWidth: '520px' }}
            overlayInnerStyle={{
                backgroundColor: '#fff',
                color: '#333',
                boxShadow: '0 4px 16px rgba(0,0,0,0.12)',
                borderRadius: '6px',
                padding: '12px'
            }}
            color="#fff"
            open={visible}
            onOpenChange={handleVisibleChange}
        >
            <span style={{ display: 'inline-flex', alignItems: 'center', gap: '4px' }}>
                <Button
                    type="link"
                    onClick={handleViewUnit}
                    style={{ padding: 0, fontWeight: '500' }}
                >
                    {unitId}
                </Button>
                <InfoCircleOutlined
                    style={{
                        fontSize: '13px',
                        color: '#1890ff',
                        cursor: 'pointer',
                        transition: 'all 0.2s',
                    }}
                    onMouseEnter={(e) => {
                        e.currentTarget.style.color = '#40a9ff';
                        e.currentTarget.style.transform = 'scale(1.1)';
                    }}
                    onMouseLeave={(e) => {
                        e.currentTarget.style.color = '#1890ff';
                        e.currentTarget.style.transform = 'scale(1)';
                    }}
                />
            </span>
        </Tooltip>
    );
};

const ApplicationDetail: React.FC = () => {
    const { appId } = useParams<{ appId: string }>();
    const navigate = useNavigate();
    const [loading, setLoading] = useState(false);
    const [application, setApplication] = useState<ApplicationData | null>(null);
    const [units, setUnits] = useState<UnitMetricsData[]>([]);
    const [filteredUnits, setFilteredUnits] = useState<UnitMetricsData[]>([]);
    const [addUnitModalVisible, setAddUnitModalVisible] = useState(false);
    const [availableUnits, setAvailableUnits] = useState<UnitMetricsData[]>([]);
    const [selectedUnits, setSelectedUnits] = useState<string[]>([]);
    const [triggeringUnitId, setTriggeringUnitId] = useState<string | null>(null);

    // 批量扫描相关状态
    const [batchScanModalVisible, setBatchScanModalVisible] = useState(false);
    const [selectedForBatch, setSelectedForBatch] = useState<string[]>([]);
    const [batchTaskTypes, setBatchTaskTypes] = useState<string[]>([]);
    const [batchTaskName, setBatchTaskName] = useState('');
    const [batchUnitSearchText, setBatchUnitSearchText] = useState('');
    const [batchScanning, setBatchScanning] = useState(false);
    const [batchScanProgressModalVisible, setBatchScanProgressModalVisible] = useState(false);
    const [currentBatchTaskId, setCurrentBatchTaskId] = useState<number | null>(null);
    const [batchScanProgress, setBatchScanProgress] = useState<any>(null);
    const [progressPolling, setProgressPolling] = useState<NodeJS.Timeout | null>(null);
    const [activeBatchTaskId, setActiveBatchTaskId] = useState<number | null>(null);

    // 筛选和排序状态
    const [searchText, setSearchText] = useState('');
    const [activityFilter, setActivityFilter] = useState<string | undefined>(undefined);
    const [dataStatusFilters, setDataStatusFilters] = useState<string[]>([]);
    const [sortField, setSortField] = useState<string>('');
    const [sortOrder, setSortOrder] = useState<'ascend' | 'descend' | undefined>(undefined);

    // 分页状态
    const [currentPage, setCurrentPage] = useState(1);
    const [pageSize, setPageSize] = useState(10);

    // 获取应用详情
    const fetchApplication = async () => {
        if (!appId) return;

        try {
            const response = await getApplication(appId);
            if (response.code === 0) {
                setApplication(response.data);
            } else {
                message.error(response.msg || '获取应用详情失败');
            }
        } catch (error) {
            console.error('获取应用详情失败:', error);
            message.error('获取应用详情失败');
        }
    };

    // 触发扫描
    const handleTriggerScan = async (unitId: string) => {
        try {
            setTriggeringUnitId(unitId);
            await manualTriggerScan(unitId);
            message.success('扫描任务已触发');
        } catch (error: any) {
            console.error('触发扫描失败:', error);
            const errorMsg = error?.response?.data?.msg || error?.message || '触发扫描失败';
            message.error(errorMsg);
        } finally {
            setTriggeringUnitId(current => (current === unitId ? null : current));
        }
    };

    // 批量扫描相关函数
    const handleBatchScan = () => {
        if (filteredUnits.length === 0) {
            message.warning('没有可扫描的单元');
            return;
        }
        setBatchScanModalVisible(true);
        // 默认选择所有单元
        setSelectedForBatch(filteredUnits.map(unit => unit.unitId));
    };

    const handleBatchScanConfirm = async () => {
        if (selectedForBatch.length === 0) {
            message.warning('请至少选择一个单元');
            return;
        }

        if (!appId) return;

        setBatchScanning(true);
        try {
            const response = await triggerBatchScan(appId, {
                taskName: batchTaskName || `批量扫描-${new Date().toLocaleString()}`,
                unitIds: selectedForBatch,
                taskTypes: batchTaskTypes.length > 0 ? batchTaskTypes : undefined,
                creator: 'system' // TODO: 从用户上下文获取
            });

            if (response.code === 0) {
                message.success('批量扫描任务已创建，可点击"查看进度"按钮查看扫描状态');

                // 关闭配置弹窗
                setBatchScanModalVisible(false);

                // 清理配置状态
                setSelectedForBatch([]);
                setBatchTaskTypes([]);
                setBatchTaskName('');
                setBatchUnitSearchText('');

                // 设置活跃的批量任务ID，用于按钮状态管理
                setActiveBatchTaskId(response.data);
                setCurrentBatchTaskId(response.data);

            } else {
                message.error(response.msg || '创建批量扫描任务失败');
            }
        } catch (error: any) {
            console.error('批量扫描失败:', error);
            const errorMsg = error?.response?.data?.msg || error?.message || '批量扫描失败';
            message.error(errorMsg);
        } finally {
            setBatchScanning(false);
        }
    };

    // 检查是否有正在运行的批量扫描任务
    const checkActiveBatchTask = async () => {
        if (!appId) return;

        try {
            // 获取批量扫描历史，检查最新的任务状态
            const response = await getBatchScanHistory(appId);
            if (response.code === 0 && response.data.length > 0) {
                const latestTask = response.data[0]; // 最新的任务
                if (latestTask.status === 'RUNNING') {
                    setActiveBatchTaskId(latestTask.batchTaskId);
                }
            }
        } catch (error) {
            console.error('检查活跃批量任务失败:', error);
        }
    };

    // 查看批量扫描进度
    const handleViewBatchProgress = () => {
        if (activeBatchTaskId) {
            setCurrentBatchTaskId(activeBatchTaskId);
            setBatchScanProgressModalVisible(true);
            startProgressPolling(activeBatchTaskId);
        }
    };

    const startProgressPolling = (batchTaskId: number) => {
        // 清除之前的轮询
        if (progressPolling) {
            clearInterval(progressPolling);
        }

        // 立即获取一次进度
        fetchBatchScanProgress(batchTaskId);

        // 设置轮询
        const interval = setInterval(() => {
            fetchBatchScanProgress(batchTaskId);
        }, 2000); // 每2秒轮询一次

        setProgressPolling(interval);
    };

    const fetchBatchScanProgress = async (batchTaskId: number) => {
        try {
            const response = await getBatchScanProgress(batchTaskId);
            if (response.code === 0) {
                setBatchScanProgress(response.data);

                // 如果完成或失败，停止轮询并清除活跃任务ID
                if (response.data.status === 'SUCCESS' || response.data.status === 'FAILED' || response.data.status === 'CANCELLED') {
                    if (progressPolling) {
                        clearInterval(progressPolling);
                        setProgressPolling(null);
                    }
                    // 清除活跃的批量任务ID，让按钮恢复到批量扫描状态
                    if (activeBatchTaskId === batchTaskId) {
                        setActiveBatchTaskId(null);
                    }
                }
            }
        } catch (error) {
            console.error('获取批量扫描进度失败:', error);
        }
    };

    const handleCancelBatchScan = async () => {
        if (!currentBatchTaskId) return;

        try {
            const response = await cancelBatchScan(currentBatchTaskId);
            if (response.code === 0) {
                message.success('批量扫描任务已取消');
                if (progressPolling) {
                    clearInterval(progressPolling);
                    setProgressPolling(null);
                }
            } else {
                message.error('取消批量扫描任务失败');
            }
        } catch (error) {
            console.error('取消批量扫描失败:', error);
            message.error('取消批量扫描任务失败');
        }
    };

    // 清理轮询
    useEffect(() => {
        return () => {
            if (progressPolling) {
                clearInterval(progressPolling);
            }
        };
    }, [progressPolling]);

    // 获取应用下的单元列表
    const fetchApplicationUnits = async () => {
        if (!appId) return;

        setLoading(true);
        try {
            const response = await getApplicationUnits(appId);
            console.log('应用单元数据响应:', response);
            if (response.code === 0) {
                console.log('单元数据详情:', response.data);
                setUnits(response.data || []);
                setFilteredUnits(response.data || []);
            } else {
                message.error(response.msg || '获取单元列表失败');
            }
        } catch (error) {
            console.error('获取单元列表失败:', error);
            message.error('获取单元列表失败');
        } finally {
            setLoading(false);
        }
    };

    // 应用筛选和排序
    useEffect(() => {
        let result = [...units];

        // 1. 搜索过滤
        if (searchText) {
            result = result.filter(unit =>
                unit.unitId?.toLowerCase().includes(searchText.toLowerCase())
            );
        }

        // 2. 活跃度筛选
        if (activityFilter) {
            result = result.filter(unit => unit.repoActivityLevel === activityFilter);
        }

        // 3. 数据状态筛选（选中的数据源必须是AVAILABLE状态）
        if (dataStatusFilters.length > 0) {
            result = result.filter(unit => {
                return dataStatusFilters.every(dataType => {
                    switch (dataType) {
                        case 'jar':
                            return unit.jarDataStatus === 'AVAILABLE';
                        case 'git':
                            return unit.gitDataStatus === 'AVAILABLE';
                        case 'apm':
                            return unit.apmDataStatus === 'AVAILABLE';
                        case 'sa':
                            return unit.saDataStatus === 'AVAILABLE';
                        default:
                            return true;
                    }
                });
            });
        }

        // 4. 排序
        if (sortField && sortOrder) {
            result.sort((a: any, b: any) => {
                let aVal = a[sortField];
                let bVal = b[sortField];

                // 处理特殊字段：疑似废弃接口数量
                if (sortField === 'suspectedDeprecatedApiCount') {
                    // APM 数据未就绪的记录总是排在最后
                    const aHasApm = a.apmDataStatus === 'AVAILABLE';
                    const bHasApm = b.apmDataStatus === 'AVAILABLE';

                    if (!aHasApm && !bHasApm) {
                        return 0; // 两个都没有 APM 数据，保持原顺序
                    }
                    if (!aHasApm) return 1; // a 没有 APM 数据，排在后面
                    if (!bHasApm) return -1; // b 没有 APM 数据，排在后面

                    // 两个都有 APM 数据，按数量排序
                    aVal = a.suspectedDeprecatedApiCount || 0;
                    bVal = b.suspectedDeprecatedApiCount || 0;
                }

                // 处理null/undefined
                if (aVal == null) aVal = 0;
                if (bVal == null) bVal = 0;

                if (sortOrder === 'ascend') {
                    return aVal > bVal ? 1 : aVal < bVal ? -1 : 0;
                } else {
                    return aVal < bVal ? 1 : aVal > bVal ? -1 : 0;
                }
            });
        }

        setFilteredUnits(result);

        // 筛选条件变化时重置到第一页
        setCurrentPage(1);
    }, [units, searchText, activityFilter, dataStatusFilters, sortField, sortOrder]);

    useEffect(() => {
        if (appId) {
            fetchApplication();
            fetchApplicationUnits();
            checkActiveBatchTask(); // 检查是否有正在运行的批量扫描任务
        }
    }, [appId]);

    // 查看单元详情
    const handleViewUnit = (unitId: string) => {
        navigate(`/unit/${unitId}`);
    };

    // 移除单元
    const handleRemoveUnit = (unitId: string) => {
        Modal.confirm({
            title: '确认移除',
            content: `确定要从应用 ${appId} 中移除单元 ${unitId} 吗？`,
            okText: '移除',
            okType: 'danger',
            cancelText: '取消',
            onOk: async () => {
                // TODO: 实现移除单元的API调用
                message.success('移除成功');
                fetchApplicationUnits();
            },
        });
    };

    // 导出到Excel
    const handleExportToExcel = () => {
        try {
            // 准备导出数据
            const exportData = filteredUnits.map((unit, index) => {
                // 检查 APM 数据是否就绪
                const hasApmData = unit.apmDataStatus === 'AVAILABLE';

                // 计算废弃接口比例
                let deprecatedCount: string | number = '--';
                let deprecatedRatio = '--';

                if (hasApmData) {
                    const total = unit.totalApiCount || 0;
                    deprecatedCount = unit.suspectedDeprecatedApiCount || 0;
                    deprecatedRatio = total > 0 ? ((deprecatedCount / total) * 100).toFixed(1) : '0.0';
                }

                // 活跃度映射
                const activityLevelMap: { [key: string]: string } = {
                    'HIGH': '高活跃',
                    'MEDIUM': '中活跃',
                    'LOW': '低活跃',
                    'UNKNOWN': '未知'
                };

                // 数据状态映射
                const statusMap: { [key: string]: string } = {
                    'AVAILABLE': '可用',
                    'UNAVAILABLE': '不可用',
                    'UNKNOWN': '未知'
                };

                return {
                    '序号': index + 1,
                    '单元ID': unit.unitId || '-',
                    '应用ID': unit.appId || '-',
                    '单元类型': '后端服务',
                    'Git仓库地址': unit.gitRepoUrl || '-',
                    '代码行数': unit.totalCodeLines || 0,
                    '文件数': unit.totalFiles || 0,
                    '代码重复率(%)': unit.duplicationPercentage ? unit.duplicationPercentage.toFixed(1) : '-',
                    '圈复杂度': unit.totalCyclomaticComplexity || '-',
                    '总接口数量': hasApmData ? (unit.totalApiCount || 0) : '--',
                    '疑似废弃接口数': deprecatedCount,
                    '废弃接口比例(%)': deprecatedRatio,
                    '仓库活跃度': activityLevelMap[unit.repoActivityLevel || 'UNKNOWN'] || '未知',
                    '年提交次数': unit.commitCountLastYear || 0,
                    'JAR数据状态': statusMap[unit.jarDataStatus || 'UNKNOWN'] || '未知',
                    'Git数据状态': statusMap[unit.gitDataStatus || 'UNKNOWN'] || '未知',
                    'APM数据状态': statusMap[unit.apmDataStatus || 'UNKNOWN'] || '未知',
                    'SA数据状态': statusMap[unit.saDataStatus || 'UNKNOWN'] || '未知',
                };
            });

            // 创建工作簿
            const worksheet = XLSX.utils.json_to_sheet(exportData);
            const workbook = XLSX.utils.book_new();
            XLSX.utils.book_append_sheet(workbook, worksheet, '单元列表');

            // 设置列宽
            const colWidths = [
                { wch: 6 },  // 序号
                { wch: 25 }, // 单元ID
                { wch: 15 }, // 应用ID
                { wch: 12 }, // 单元类型
                { wch: 60 }, // Git仓库地址
                { wch: 12 }, // 代码行数
                { wch: 10 }, // 文件数
                { wch: 15 }, // 代码重复率
                { wch: 12 }, // 圈复杂度
                { wch: 12 }, // 总接口数量
                { wch: 15 }, // 疑似废弃接口数
                { wch: 16 }, // 废弃接口比例
                { wch: 12 }, // 仓库活跃度
                { wch: 12 }, // 年提交次数
                { wch: 13 }, // JAR数据状态
                { wch: 13 }, // Git数据状态
                { wch: 13 }, // APM数据状态
                { wch: 12 }, // SA数据状态
            ];
            worksheet['!cols'] = colWidths;

            // 生成文件名
            const fileName = `${application?.appName || appId}_单元列表_${new Date().toISOString().split('T')[0]}.xlsx`;

            // 下载文件
            XLSX.writeFile(workbook, fileName);
            message.success(`成功导出 ${filteredUnits.length} 条数据`);
        } catch (error) {
            console.error('导出失败:', error);
            message.error('导出失败，请重试');
        }
    };

    // 表格列定义
    const columns = [
        {
            title: (
                <div style={{
                    display: 'flex',
                    alignItems: 'center',
                    gap: '6px',
                    padding: '4px 0',
                    fontWeight: '600',
                    fontSize: '13px',
                    color: '#1890ff'
                }}>
                    <IdcardOutlined style={{ fontSize: '14px' }} />
                    <span>基本信息</span>
                </div>
            ),
            children: [
                {
                    title: '单元ID',
                    dataIndex: 'unitId',
                    key: 'unitId',
                    width: 180,
                    fixed: 'left' as const,
                    render: (text: string, record: UnitMetricsData) => {
                        return <UnitInfoTooltip unitId={text} />;
                    },
                },
                {
                    title: '应用ID',
                    dataIndex: 'appId',
                    key: 'appId',
                    width: 120,
                    render: (text: string) => text || '-',
                },
                {
                    title: '单元类型',
                    dataIndex: 'unitType',
                    key: 'unitType',
                    width: 100,
                    render: () => '后端服务',
                },
            ]
        },
        {
            title: (
                <div style={{
                    display: 'flex',
                    alignItems: 'center',
                    gap: '6px',
                    padding: '4px 0',
                    fontWeight: '600',
                    fontSize: '13px',
                    color: '#52c41a'
                }}>
                    <CodeOutlined style={{ fontSize: '14px' }} />
                    <span>代码信息</span>
                </div>
            ),
            children: [
                {
                    title: '代码行',
                    dataIndex: 'totalCodeLines',
                    key: 'totalCodeLines',
                    width: 100,
                    sorter: true,
                    render: (lines: number) => {
                        if (!lines) return '0';
                        return lines > 1000 ? `${(lines / 1000).toFixed(1)}K` : lines.toString();
                    },
                },
                {
                    title: '文件数',
                    dataIndex: 'totalFiles',
                    key: 'totalFiles',
                    width: 80,
                    sorter: true,
                    render: (files: number) => files || 0,
                },
                {
                    title: '代码重复率',
                    dataIndex: 'duplicationPercentage',
                    key: 'duplicationPercentage',
                    width: 100,
                    sorter: true,
                    render: (percentage: number) => {
                        if (percentage === null || percentage === undefined) return '-';
                        const value = typeof percentage === 'number' ? percentage : parseFloat(percentage);
                        return isNaN(value) ? '-' : `${value.toFixed(1)}%`;
                    },
                },
                {
                    title: '圈复杂度',
                    dataIndex: 'totalCyclomaticComplexity',
                    key: 'totalCyclomaticComplexity',
                    width: 100,
                    sorter: true,
                    align: 'right' as const,
                    render: (total: number) => {
                        if (total === null || total === undefined) {
                            return '-';
                        }

                        return (
                            <span style={{ fontWeight: '600', color: '#1890ff', fontSize: '14px' }}>
                                {total}
                            </span>
                        );
                    },
                },
            ]
        },
        {
            title: (
                <div style={{
                    display: 'flex',
                    alignItems: 'center',
                    gap: '6px',
                    padding: '4px 0',
                    fontWeight: '600',
                    fontSize: '13px',
                    color: '#fa8c16'
                }}>
                    <ApiOutlined style={{ fontSize: '14px' }} />
                    <span>接口信息</span>
                </div>
            ),
            children: [
                {
                    title: '总接口数量',
                    dataIndex: 'totalApiCount',
                    key: 'totalApiCount',
                    width: 100,
                    align: 'right' as const,
                    sorter: true,
                    render: (count: number) => (
                        <span style={{ fontWeight: '600', color: '#1890ff', fontSize: '14px' }}>
                            {count || 0}
                        </span>
                    )
                },
                {
                    title: '疑似废弃接口',
                    dataIndex: 'suspectedDeprecatedApiCount',
                    key: 'suspectedDeprecatedApiCount',
                    width: 140,
                    align: 'center' as const,
                    sorter: true,
                    render: (count: number, record: UnitMetricsData) => {
                        // 如果 APM 数据未就绪，显示 --
                        if (record.apmDataStatus !== 'AVAILABLE') {
                            return <span style={{ color: '#d9d9d9' }}>--</span>;
                        }

                        const total = (record as any).totalApiCount || 0;
                        const ratio = total > 0 ? ((count || 0) / total * 100).toFixed(1) : '0.0';
                        const isHigh = parseFloat(ratio) > 20;

                        return (
                            <span style={{ fontFamily: 'monospace', fontSize: '12px' }}>
                                <span style={{
                                    fontWeight: '600',
                                    color: isHigh ? '#ff4d4f' : '#52c41a',
                                    fontSize: '14px'
                                }}>
                                    {count || 0}
                                </span>
                                <span style={{ margin: '0 4px', color: '#999' }}>/</span>
                                <span style={{ fontSize: '11px', color: '#999' }}>
                                    {ratio}%
                                </span>
                            </span>
                        );
                    }
                },
            ]
        },
        {
            title: (
                <div style={{
                    display: 'flex',
                    alignItems: 'center',
                    gap: '6px',
                    padding: '4px 0',
                    fontWeight: '600',
                    fontSize: '13px',
                    color: '#722ed1'
                }}>
                    <BranchesOutlined style={{ fontSize: '14px' }} />
                    <span>仓库信息</span>
                </div>
            ),
            children: [
                {
                    title: '仓库活跃度',
                    dataIndex: 'commitCountLastYear',
                    key: 'commitCountLastYear',
                    width: 140,
                    align: 'center' as const,
                    sorter: true,
                    render: (_: any, record: UnitMetricsData) => {
                        const level = record.repoActivityLevel || 'UNKNOWN';
                        const commitCount = record.commitCountLastYear || 0;

                        const configs: { [key: string]: { text: string; color: string } } = {
                            'HIGH': { text: '高活跃', color: 'green' },
                            'MEDIUM': { text: '中活跃', color: 'orange' },
                            'LOW': { text: '低活跃', color: 'red' },
                            'UNKNOWN': { text: '未知', color: 'default' }
                        };
                        const config = configs[level] || configs['UNKNOWN'];

                        return (
                            <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', gap: '6px' }}>
                                <Tag color={config.color} style={{ margin: 0 }}>{config.text}</Tag>
                                {commitCount > 0 && (
                                    <span style={{ fontSize: '11px', color: '#999', whiteSpace: 'nowrap' }}>
                                        {commitCount}次/年
                                    </span>
                                )}
                            </div>
                        );
                    }
                },
            ]
        },
        {
            title: '数据就绪情况',
            key: 'dataReadiness',
            width: 160,
            render: (_: any, record: UnitMetricsData) => {
                const getStatusColor = (status: string) => {
                    switch (status) {
                        case 'AVAILABLE':
                            return '#52c41a'; // 绿色
                        case 'UNAVAILABLE':
                            return '#ff4d4f'; // 红色
                        case 'UNKNOWN':
                        default:
                            return '#d9d9d9'; // 灰色
                    }
                };

                const getStatusIcon = (status: string) => {
                    switch (status) {
                        case 'AVAILABLE':
                            return '●'; // 实心圆点
                        case 'UNAVAILABLE':
                            return '●'; // 实心圆点
                        case 'UNKNOWN':
                        default:
                            return '○'; // 空心圆点
                    }
                };

                const dataTypes = [
                    { key: 'jar', label: 'JAR', status: record.jarDataStatus },
                    { key: 'git', label: 'Git', status: record.gitDataStatus },
                    { key: 'apm', label: 'APM', status: record.apmDataStatus },
                    { key: 'sa', label: 'SA', status: record.saDataStatus },
                ];

                return (
                    <div style={{ display: 'flex', gap: '6px', alignItems: 'center', flexWrap: 'wrap' }}>
                        {dataTypes.map(({ key, label, status }) => (
                            <span
                                key={key}
                                style={{
                                    display: 'inline-flex',
                                    alignItems: 'center',
                                    gap: '2px',
                                    fontSize: '11px',
                                    fontWeight: '500',
                                    color: '#666',
                                }}
                                title={`${label}数据: ${status || 'UNKNOWN'}`}
                            >
                                <span
                                    style={{
                                        color: getStatusColor(status || 'UNKNOWN'),
                                        fontSize: '8px',
                                        lineHeight: 1,
                                    }}
                                >
                                    {getStatusIcon(status || 'UNKNOWN')}
                                </span>
                                {label}
                            </span>
                        ))}
                    </div>
                );
            },
        },
        {
            title: '操作',
            key: 'action',
            width: 160,
            fixed: 'right' as const,
            render: (_: any, record: UnitMetricsData) => (
                <Space size="small">
                    <Button
                        type="text"
                        size="small"
                        icon={<EyeOutlined />}
                        onClick={() => handleViewUnit(record.unitId)}
                        title="查看详情"
                    />
                    <Button
                        type="text"
                        size="small"
                        icon={<ScanOutlined />}
                        onClick={() => handleTriggerScan(record.unitId)}
                        loading={triggeringUnitId === record.unitId}
                        style={{ color: '#722ed1' }}
                        title="触发扫描"
                    />
                    <Button
                        type="text"
                        size="small"
                        icon={<DeleteOutlined />}
                        onClick={() => handleRemoveUnit(record.unitId)}
                        danger
                        title="移除"
                    />
                </Space>
            ),
        },
    ];

    if (!application) {
        return <div>加载中...</div>;
    }

    return (
        <div style={{ padding: '24px', background: '#f5f5f5', minHeight: '100vh' }}>
            {/* 面包屑导航 */}
            <Breadcrumb style={{ marginBottom: '24px' }}>
                <Breadcrumb.Item>
                    <Button
                        type="link"
                        icon={<ArrowLeftOutlined />}
                        onClick={() => navigate('/metrics')}
                        style={{ padding: 0 }}
                    >
                        应用度量
                    </Button>
                </Breadcrumb.Item>
                <Breadcrumb.Item>{application.appName}应用详情</Breadcrumb.Item>
            </Breadcrumb>

            {/* 应用信息卡片 */}
            <Card style={{ marginBottom: '24px' }}>
                <Row gutter={24}>
                    <Col span={8}>
                        <div>
                            <div style={{ color: '#666', marginBottom: '8px' }}>应用名称</div>
                            <div style={{ fontSize: '16px', fontWeight: '500' }}>{application.appName}</div>
                        </div>
                    </Col>
                    <Col span={8}>
                        <div>
                            <div style={{ color: '#666', marginBottom: '8px' }}>应用ID</div>
                            <div style={{ fontSize: '16px', fontWeight: '500' }}>{application.appId}</div>
                        </div>
                    </Col>
                    <Col span={8}>
                        <div>
                            <div style={{ color: '#666', marginBottom: '8px' }}>归属团队</div>
                            <div style={{ fontSize: '16px', fontWeight: '500' }}>{application.ownTeam || '-'}</div>
                        </div>
                    </Col>
                </Row>
            </Card>

            {/* 统计信息卡片 */}
            <Row gutter={16} style={{ marginBottom: '24px' }}>
                <Col span={6}>
                    <Card>
                        <div style={{ textAlign: 'center' }}>
                            <div style={{ fontSize: '24px', fontWeight: 'bold', color: '#1890ff' }}>
                                {units.length}
                            </div>
                            <div style={{ color: '#666', marginTop: '8px' }}>单元数量</div>
                        </div>
                    </Card>
                </Col>
                <Col span={6}>
                    <Card>
                        <div style={{ textAlign: 'center' }}>
                            <div style={{ fontSize: '24px', fontWeight: 'bold', color: '#52c41a' }}>
                                {units.reduce((sum, unit) => sum + (unit.totalCodeLines || 0), 0) > 1000
                                    ? `${(units.reduce((sum, unit) => sum + (unit.totalCodeLines || 0), 0) / 1000).toFixed(0)}K`
                                    : units.reduce((sum, unit) => sum + (unit.totalCodeLines || 0), 0)
                                }
                            </div>
                            <div style={{ color: '#666', marginTop: '8px' }}>总代码行</div>
                        </div>
                    </Card>
                </Col>
                <Col span={6}>
                    <Card>
                        <div style={{ textAlign: 'center' }}>
                            <div style={{ fontSize: '24px', fontWeight: 'bold', color: '#fa8c16' }}>
                                {units.length > 0
                                    ? (units.reduce((sum, unit) => sum + (unit.avgCyclomaticComplexity || 0), 0) / units.length).toFixed(1)
                                    : '0'
                                }
                            </div>
                            <div style={{ color: '#666', marginTop: '8px' }}>平均复杂度</div>
                        </div>
                    </Card>
                </Col>
                <Col span={6}>
                    <Card>
                        <div style={{ textAlign: 'center' }}>
                            <div style={{ fontSize: '24px', fontWeight: 'bold', color: '#f5222d' }}>
                                {units.length > 0
                                    ? (units.reduce((sum, unit) => sum + (unit.duplicationPercentage || 0), 0) / units.length).toFixed(1)
                                    : '0'
                                }%
                            </div>
                            <div style={{ color: '#666', marginTop: '8px' }}>平均重复率</div>
                        </div>
                    </Card>
                </Col>
            </Row>

            {/* 应用下单元列表 */}
            <Card
                title="应用下单元列表"
                extra={
                    <Space>
                        <Button
                            icon={<DownloadOutlined />}
                            onClick={handleExportToExcel}
                            disabled={filteredUnits.length === 0}
                        >
                            导出Excel
                        </Button>
                        <Button
                            icon={activeBatchTaskId ? <EyeOutlined /> : <PlayCircleOutlined />}
                            onClick={activeBatchTaskId ? handleViewBatchProgress : handleBatchScan}
                            disabled={!activeBatchTaskId && filteredUnits.length === 0}
                            style={{ color: '#722ed1' }}
                        >
                            {activeBatchTaskId ? '查看进度' : '批量扫描'}
                        </Button>
                        {activeBatchTaskId && (
                            <Tag color="processing" style={{ marginLeft: '8px' }}>
                                <span style={{ fontSize: '11px' }}>
                                    批量任务进行中...
                                </span>
                            </Tag>
                        )}
                        <Button
                            type="primary"
                            icon={<PlusOutlined />}
                            onClick={() => setAddUnitModalVisible(true)}
                        >
                            添加单元
                        </Button>
                    </Space>
                }
            >
                {/* 筛选区域 */}
                <Space direction="vertical" size="middle" style={{ width: '100%', marginBottom: '16px' }}>
                    <Row gutter={16}>
                        <Col span={8}>
                            <Input
                                placeholder="搜索单元ID"
                                prefix={<SearchOutlined />}
                                value={searchText}
                                onChange={(e) => setSearchText(e.target.value)}
                                allowClear
                            />
                        </Col>
                        <Col span={4}>
                            <Select
                                placeholder="仓库活跃度"
                                style={{ width: '100%' }}
                                value={activityFilter}
                                onChange={setActivityFilter}
                                allowClear
                            >
                                <Option value="HIGH">高活跃</Option>
                                <Option value="MEDIUM">中活跃</Option>
                                <Option value="LOW">低活跃</Option>
                                <Option value="UNKNOWN">未知</Option>
                            </Select>
                        </Col>
                        <Col span={6}>
                            <Select
                                mode="multiple"
                                placeholder="数据就绪（选中必须可用）"
                                style={{ width: '100%' }}
                                value={dataStatusFilters}
                                onChange={setDataStatusFilters}
                                maxTagCount="responsive"
                                allowClear
                            >
                                <Option value="jar">JAR</Option>
                                <Option value="git">GIT</Option>
                                <Option value="apm">APM</Option>
                                <Option value="sa">SA</Option>
                            </Select>
                        </Col>
                        <Col span={4}>
                            <Button
                                icon={<FilterOutlined />}
                                onClick={() => {
                                    setSearchText('');
                                    setActivityFilter(undefined);
                                    setDataStatusFilters([]);
                                    setSortField('');
                                    setSortOrder(undefined);
                                    setCurrentPage(1);
                                    setPageSize(10);
                                }}
                            >
                                重置筛选
                            </Button>
                        </Col>
                    </Row>
                </Space>

                <Table
                    columns={columns.map(col => {
                        // 如果是分组列，递归处理子列
                        if (col.children) {
                            return {
                                ...col,
                                children: col.children.map((childCol: any) => ({
                                    ...childCol,
                                    sortOrder: childCol.key === sortField ? sortOrder : null,
                                }))
                            };
                        }
                        // 普通列直接处理
                        return {
                            ...col,
                            sortOrder: col.key === sortField ? sortOrder : null,
                        };
                    })}
                    dataSource={filteredUnits}
                    loading={loading}
                    pagination={{
                        current: currentPage,
                        pageSize: pageSize,
                        total: filteredUnits.length,
                        showSizeChanger: true,
                        pageSizeOptions: ['10', '20', '50', '100'],
                        showTotal: (total, range) =>
                            `显示第 ${range[0]}-${range[1]} 条，共 ${total} 条记录`,
                    }}
                    rowKey="unitId"
                    scroll={{
                        x: 1760,
                        y: 'calc(100vh - 660px)' // 调整高度，为分页器留出空间
                    }}
                    size="middle"
                    onChange={(pagination, filters, sorter: any) => {
                        // 处理分页变化
                        if (pagination.current !== currentPage) {
                            setCurrentPage(pagination.current || 1);
                        }
                        if (pagination.pageSize !== pageSize) {
                            setPageSize(pagination.pageSize || 10);
                            setCurrentPage(1); // 改变每页数量时重置到第一页
                        }

                        // 处理排序变化
                        if (sorter.field) {
                            setSortField(sorter.field);
                            setSortOrder(sorter.order);
                        } else {
                            setSortField('');
                            setSortOrder(undefined);
                        }
                    }}
                />
            </Card>

            {/* 添加单元弹窗 */}
            <Modal
                title="添加单元"
                open={addUnitModalVisible}
                onCancel={() => {
                    setAddUnitModalVisible(false);
                    setSelectedUnits([]);
                }}
                onOk={async () => {
                    // TODO: 实现添加单元的API调用
                    message.success('添加成功');
                    setAddUnitModalVisible(false);
                    setSelectedUnits([]);
                    fetchApplicationUnits();
                }}
                width={600}
            >
                <div style={{ marginBottom: '16px' }}>
                    请选择要添加到应用 <strong>{application.appName}</strong> 的单元：
                </div>
                <Select
                    mode="multiple"
                    style={{ width: '100%' }}
                    placeholder="选择单元"
                    value={selectedUnits}
                    onChange={setSelectedUnits}
                    showSearch
                    filterOption={(input, option) =>
                        option?.children?.toString().toLowerCase().includes(input.toLowerCase()) || false
                    }
                >
                    {availableUnits.map(unit => (
                        <Option key={unit.unitId} value={unit.unitId}>
                            {unit.unitId}
                        </Option>
                    ))}
                </Select>
            </Modal>

            {/* 批量扫描配置弹窗 */}
            <Modal
                title={
                    <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
                        <PlayCircleOutlined style={{ color: '#722ed1' }} />
                        <span>批量扫描配置</span>
                    </div>
                }
                open={batchScanModalVisible}
                onCancel={() => {
                    setBatchScanModalVisible(false);
                    setSelectedForBatch([]);
                    setBatchTaskTypes([]);
                    setBatchTaskName('');
                    setBatchUnitSearchText('');
                }}
                onOk={handleBatchScanConfirm}
                confirmLoading={batchScanning}
                width={1000}
                styles={{
                    body: { padding: '24px' }
                }}
            >
                <Space direction="vertical" size="large" style={{ width: '100%' }}>
                    {/* 任务基本信息 */}
                    <div>
                        <div style={{ marginBottom: '12px', fontSize: '14px', fontWeight: '600', color: '#262626' }}>
                            <IdcardOutlined style={{ marginRight: '6px', color: '#1890ff' }} />
                            任务基本信息
                        </div>
                        <Input
                            placeholder="请输入任务名称（可选，不填写将自动生成）"
                            value={batchTaskName}
                            onChange={(e) => setBatchTaskName(e.target.value)}
                            prefix={<span style={{ color: '#8c8c8c', fontSize: '12px' }}>任务名称</span>}
                            style={{ borderRadius: '6px' }}
                        />
                    </div>

                    {/* 扫描任务类型选择 */}
                    <div>
                        <div style={{ marginBottom: '12px', fontSize: '14px', fontWeight: '600', color: '#262626' }}>
                            <ApiOutlined style={{ marginRight: '6px', color: '#52c41a' }} />
                            扫描任务类型选择
                            <span style={{ marginLeft: '8px', fontSize: '12px', color: '#8c8c8c', fontWeight: '400' }}>
                                （不选择则执行全部任务类型）
                            </span>
                        </div>
                        <div style={{
                            background: '#fafafa',
                            padding: '16px',
                            borderRadius: '8px',
                            border: '1px solid #f0f0f0'
                        }}>
                            <Checkbox.Group
                                value={batchTaskTypes}
                                onChange={setBatchTaskTypes}
                                style={{ width: '100%' }}
                            >
                                <Row gutter={[12, 12]}>
                                    <Col span={8}>
                                        <div style={{
                                            background: '#fff',
                                            padding: '12px',
                                            borderRadius: '6px',
                                            border: '1px solid #e8e8e8',
                                            transition: 'all 0.3s',
                                            cursor: 'pointer'
                                        }}
                                            onMouseEnter={(e) => {
                                                e.currentTarget.style.borderColor = '#1890ff';
                                                e.currentTarget.style.boxShadow = '0 2px 8px rgba(24, 144, 255, 0.1)';
                                            }}
                                            onMouseLeave={(e) => {
                                                e.currentTarget.style.borderColor = '#e8e8e8';
                                                e.currentTarget.style.boxShadow = 'none';
                                            }}>
                                            <Checkbox value="JAR" style={{ marginBottom: '4px' }}>
                                                <span style={{ fontWeight: '500' }}>JAR分析</span>
                                            </Checkbox>
                                            <div style={{ fontSize: '11px', color: '#8c8c8c', marginLeft: '24px' }}>
                                                静态代码分析
                                            </div>
                                        </div>
                                    </Col>
                                    <Col span={8}>
                                        <div style={{
                                            background: '#fff',
                                            padding: '12px',
                                            borderRadius: '6px',
                                            border: '1px solid #e8e8e8',
                                            transition: 'all 0.3s',
                                            cursor: 'pointer'
                                        }}
                                            onMouseEnter={(e) => {
                                                e.currentTarget.style.borderColor = '#1890ff';
                                                e.currentTarget.style.boxShadow = '0 2px 8px rgba(24, 144, 255, 0.1)';
                                            }}
                                            onMouseLeave={(e) => {
                                                e.currentTarget.style.borderColor = '#e8e8e8';
                                                e.currentTarget.style.boxShadow = 'none';
                                            }}>
                                            <Checkbox value="GIT" style={{ marginBottom: '4px' }}>
                                                <span style={{ fontWeight: '500' }}>Git分析</span>
                                            </Checkbox>
                                            <div style={{ fontSize: '11px', color: '#8c8c8c', marginLeft: '24px' }}>
                                                仓库活跃度分析
                                            </div>
                                        </div>
                                    </Col>
                                    <Col span={8}>
                                        <div style={{
                                            background: '#fff',
                                            padding: '12px',
                                            borderRadius: '6px',
                                            border: '1px solid #e8e8e8',
                                            transition: 'all 0.3s',
                                            cursor: 'pointer'
                                        }}
                                            onMouseEnter={(e) => {
                                                e.currentTarget.style.borderColor = '#1890ff';
                                                e.currentTarget.style.boxShadow = '0 2px 8px rgba(24, 144, 255, 0.1)';
                                            }}
                                            onMouseLeave={(e) => {
                                                e.currentTarget.style.borderColor = '#e8e8e8';
                                                e.currentTarget.style.boxShadow = 'none';
                                            }}>
                                            <Checkbox value="APM" style={{ marginBottom: '4px' }}>
                                                <span style={{ fontWeight: '500' }}>APM分析</span>
                                            </Checkbox>
                                            <div style={{ fontSize: '11px', color: '#8c8c8c', marginLeft: '24px' }}>
                                                应用性能监控
                                            </div>
                                        </div>
                                    </Col>
                                    <Col span={8}>
                                        <div style={{
                                            background: '#fff',
                                            padding: '12px',
                                            borderRadius: '6px',
                                            border: '1px solid #e8e8e8',
                                            transition: 'all 0.3s',
                                            cursor: 'pointer'
                                        }}
                                            onMouseEnter={(e) => {
                                                e.currentTarget.style.borderColor = '#1890ff';
                                                e.currentTarget.style.boxShadow = '0 2px 8px rgba(24, 144, 255, 0.1)';
                                            }}
                                            onMouseLeave={(e) => {
                                                e.currentTarget.style.borderColor = '#e8e8e8';
                                                e.currentTarget.style.boxShadow = 'none';
                                            }}>
                                            <Checkbox value="SA" style={{ marginBottom: '4px' }}>
                                                <span style={{ fontWeight: '500' }}>SA分析</span>
                                            </Checkbox>
                                            <div style={{ fontSize: '11px', color: '#8c8c8c', marginLeft: '24px' }}>
                                                服务架构分析
                                            </div>
                                        </div>
                                    </Col>
                                    <Col span={8}>
                                        <div style={{
                                            background: '#fff',
                                            padding: '12px',
                                            borderRadius: '6px',
                                            border: '1px solid #e8e8e8',
                                            transition: 'all 0.3s',
                                            cursor: 'pointer'
                                        }}
                                            onMouseEnter={(e) => {
                                                e.currentTarget.style.borderColor = '#1890ff';
                                                e.currentTarget.style.boxShadow = '0 2px 8px rgba(24, 144, 255, 0.1)';
                                            }}
                                            onMouseLeave={(e) => {
                                                e.currentTarget.style.borderColor = '#e8e8e8';
                                                e.currentTarget.style.boxShadow = 'none';
                                            }}>
                                            <Checkbox value="STATISTICS" style={{ marginBottom: '4px' }}>
                                                <span style={{ fontWeight: '500' }}>统计分析</span>
                                            </Checkbox>
                                            <div style={{ fontSize: '11px', color: '#8c8c8c', marginLeft: '24px' }}>
                                                代码统计汇总
                                            </div>
                                        </div>
                                    </Col>
                                    <Col span={8}>
                                        <div style={{
                                            background: '#fff',
                                            padding: '12px',
                                            borderRadius: '6px',
                                            border: '1px solid #e8e8e8',
                                            transition: 'all 0.3s',
                                            cursor: 'pointer'
                                        }}
                                            onMouseEnter={(e) => {
                                                e.currentTarget.style.borderColor = '#1890ff';
                                                e.currentTarget.style.boxShadow = '0 2px 8px rgba(24, 144, 255, 0.1)';
                                            }}
                                            onMouseLeave={(e) => {
                                                e.currentTarget.style.borderColor = '#e8e8e8';
                                                e.currentTarget.style.boxShadow = 'none';
                                            }}>
                                            <Checkbox value="DEPRECATION_ANALYSIS" style={{ marginBottom: '4px' }}>
                                                <span style={{ fontWeight: '500' }}>废弃分析</span>
                                            </Checkbox>
                                            <div style={{ fontSize: '11px', color: '#8c8c8c', marginLeft: '24px' }}>
                                                废弃接口识别
                                            </div>
                                        </div>
                                    </Col>
                                </Row>
                            </Checkbox.Group>
                        </div>
                    </div>

                    <Divider style={{ margin: '16px 0' }} />

                    {/* 单元选择区域 */}
                    <div>
                        <div style={{ marginBottom: '12px', fontSize: '14px', fontWeight: '600', color: '#262626' }}>
                            <BranchesOutlined style={{ marginRight: '6px', color: '#722ed1' }} />
                            选择要扫描的单元
                            <Tag color="blue" style={{ marginLeft: '8px', fontSize: '11px' }}>
                                {selectedForBatch.length}/{(() => {
                                    // 根据搜索文本过滤单元
                                    const searchFilteredUnits = batchUnitSearchText ?
                                        filteredUnits.filter(unit =>
                                            unit.unitId?.toLowerCase().includes(batchUnitSearchText.toLowerCase())
                                        ) : filteredUnits;
                                    return searchFilteredUnits.length;
                                })()}
                            </Tag>
                        </div>

                        {/* 搜索和批量操作 */}
                        <div style={{ marginBottom: '12px', display: 'flex', gap: '12px', alignItems: 'center' }}>
                            <Input
                                placeholder="搜索单元ID..."
                                prefix={<SearchOutlined style={{ color: '#bfbfbf' }} />}
                                value={batchUnitSearchText}
                                onChange={(e) => setBatchUnitSearchText(e.target.value)}
                                style={{ flex: 1, borderRadius: '6px' }}
                                allowClear
                            />
                            <Space>
                                <Button
                                    size="small"
                                    type="primary"
                                    ghost
                                    onClick={() => {
                                        const searchFilteredUnits = batchUnitSearchText ?
                                            filteredUnits.filter(unit =>
                                                unit.unitId?.toLowerCase().includes(batchUnitSearchText.toLowerCase())
                                            ) : filteredUnits;
                                        setSelectedForBatch(searchFilteredUnits.map(unit => unit.unitId));
                                    }}
                                >
                                    全选当前
                                </Button>
                                <Button
                                    size="small"
                                    onClick={() => setSelectedForBatch([])}
                                >
                                    清空选择
                                </Button>
                            </Space>
                        </div>

                        {/* 单元列表 */}
                        <div style={{
                            background: '#fafafa',
                            borderRadius: '8px',
                            border: '1px solid #f0f0f0',
                            maxHeight: '320px',
                            overflowY: 'auto',
                            padding: '12px'
                        }}>
                            <Checkbox.Group
                                value={selectedForBatch}
                                onChange={setSelectedForBatch}
                                style={{ width: '100%' }}
                            >
                                <Row gutter={[8, 8]}>
                                    {(() => {
                                        // 根据搜索文本过滤单元
                                        const searchFilteredUnits = batchUnitSearchText ?
                                            filteredUnits.filter(unit =>
                                                unit.unitId?.toLowerCase().includes(batchUnitSearchText.toLowerCase())
                                            ) : filteredUnits;

                                        if (searchFilteredUnits.length === 0) {
                                            return (
                                                <Col span={24}>
                                                    <div style={{
                                                        textAlign: 'center',
                                                        padding: '40px 20px',
                                                        color: '#999',
                                                        background: '#fff',
                                                        borderRadius: '6px'
                                                    }}>
                                                        <SearchOutlined style={{ fontSize: '24px', marginBottom: '8px' }} />
                                                        <div>
                                                            {batchUnitSearchText ? '未找到匹配的单元' : '暂无可选单元'}
                                                        </div>
                                                    </div>
                                                </Col>
                                            );
                                        }

                                        return searchFilteredUnits.map(unit => (
                                            <Col span={6} key={unit.unitId}>
                                                <div style={{
                                                    background: '#fff',
                                                    padding: '8px 12px',
                                                    borderRadius: '6px',
                                                    border: '1px solid #e8e8e8',
                                                    transition: 'all 0.2s',
                                                    cursor: 'pointer',
                                                    fontSize: '12px'
                                                }}
                                                    onMouseEnter={(e) => {
                                                        e.currentTarget.style.borderColor = '#1890ff';
                                                        e.currentTarget.style.backgroundColor = '#f6ffed';
                                                    }}
                                                    onMouseLeave={(e) => {
                                                        e.currentTarget.style.borderColor = '#e8e8e8';
                                                        e.currentTarget.style.backgroundColor = '#fff';
                                                    }}>
                                                    <Checkbox value={unit.unitId}>
                                                        <span style={{
                                                            fontWeight: '500',
                                                            color: selectedForBatch.includes(unit.unitId) ? '#1890ff' : '#262626'
                                                        }}>
                                                            {unit.unitId}
                                                        </span>
                                                    </Checkbox>
                                                </div>
                                            </Col>
                                        ));
                                    })()}
                                </Row>
                            </Checkbox.Group>
                        </div>

                        {/* 选择汇总信息 */}
                        {selectedForBatch.length > 0 && (
                            <div style={{
                                marginTop: '12px',
                                padding: '12px',
                                background: '#e6f7ff',
                                borderRadius: '6px',
                                border: '1px solid #91d5ff',
                                fontSize: '13px'
                            }}>
                                <InfoCircleOutlined style={{ color: '#1890ff', marginRight: '6px' }} />
                                已选择 <strong style={{ color: '#1890ff' }}>{selectedForBatch.length}</strong> 个单元进行批量扫描
                                {batchTaskTypes.length > 0 && (
                                    <span style={{ marginLeft: '8px' }}>
                                        ，执行任务类型：<strong style={{ color: '#1890ff' }}>{batchTaskTypes.join('、')}</strong>
                                    </span>
                                )}
                                {batchTaskTypes.length === 0 && (
                                    <span style={{ marginLeft: '8px' }}>
                                        ，执行<strong style={{ color: '#1890ff' }}>全部任务类型</strong>
                                    </span>
                                )}
                            </div>
                        )}
                    </div>
                </Space>
            </Modal>

            {/* 批量扫描进度弹窗 */}
            <Modal
                title="批量扫描进度"
                open={batchScanProgressModalVisible}
                onCancel={() => {
                    setBatchScanProgressModalVisible(false);
                    if (progressPolling) {
                        clearInterval(progressPolling);
                        setProgressPolling(null);
                    }
                }}
                footer={[
                    <Button
                        key="cancel"
                        danger
                        icon={<CloseCircleOutlined />}
                        onClick={handleCancelBatchScan}
                        disabled={!batchScanProgress || batchScanProgress.status !== 'RUNNING'}
                    >
                        取消扫描
                    </Button>,
                    <Button
                        key="close"
                        onClick={() => {
                            setBatchScanProgressModalVisible(false);
                            if (progressPolling) {
                                clearInterval(progressPolling);
                                setProgressPolling(null);
                            }
                        }}
                    >
                        关闭
                    </Button>
                ]}
                width={800}
            >
                {batchScanProgress && (
                    <Space direction="vertical" size="middle" style={{ width: '100%' }}>
                        {/* 总体进度 */}
                        <div>
                            <div style={{ marginBottom: '8px', display: 'flex', justifyContent: 'space-between' }}>
                                <span>总体进度:</span>
                                <span>{batchScanProgress.progressPercentage?.toFixed(1)}%</span>
                            </div>
                            <Progress
                                percent={batchScanProgress.progressPercentage}
                                status={batchScanProgress.status === 'RUNNING' ? 'active' :
                                    batchScanProgress.status === 'SUCCESS' ? 'success' : 'exception'}
                                strokeColor={batchScanProgress.status === 'RUNNING' ? '#1890ff' :
                                    batchScanProgress.status === 'SUCCESS' ? '#52c41a' : '#ff4d4f'}
                            />
                        </div>

                        {/* 统计信息 */}
                        <Row gutter={16}>
                            <Col span={6}>
                                <div style={{ textAlign: 'center', padding: '16px', background: '#f5f5f5', borderRadius: '6px' }}>
                                    <div style={{ fontSize: '24px', fontWeight: 'bold', color: '#1890ff' }}>
                                        {batchScanProgress.totalUnits}
                                    </div>
                                    <div style={{ color: '#666' }}>总单元数</div>
                                </div>
                            </Col>
                            <Col span={6}>
                                <div style={{ textAlign: 'center', padding: '16px', background: '#f6ffed', borderRadius: '6px' }}>
                                    <div style={{ fontSize: '24px', fontWeight: 'bold', color: '#52c41a' }}>
                                        {batchScanProgress.completedUnits}
                                    </div>
                                    <div style={{ color: '#666' }}>已完成</div>
                                </div>
                            </Col>
                            <Col span={6}>
                                <div style={{ textAlign: 'center', padding: '16px', background: '#fff2f0', borderRadius: '6px' }}>
                                    <div style={{ fontSize: '24px', fontWeight: 'bold', color: '#ff4d4f' }}>
                                        {batchScanProgress.failedUnits}
                                    </div>
                                    <div style={{ color: '#666' }}>失败</div>
                                </div>
                            </Col>
                            <Col span={6}>
                                <div style={{ textAlign: 'center', padding: '16px', background: '#f0f5ff', borderRadius: '6px' }}>
                                    <div style={{ fontSize: '24px', fontWeight: 'bold', color: '#722ed1' }}>
                                        {batchScanProgress.currentUnitIndex + 1}
                                    </div>
                                    <div style={{ color: '#666' }}>当前执行</div>
                                </div>
                            </Col>
                        </Row>

                        {/* 状态提示 */}
                        <Alert
                            message={
                                batchScanProgress.status === 'RUNNING' ? '扫描进行中...' :
                                    batchScanProgress.status === 'SUCCESS' ? '扫描已完成' :
                                        batchScanProgress.status === 'FAILED' ? '扫描失败' :
                                            batchScanProgress.status === 'CANCELLED' ? '扫描已取消' : '未知状态'
                            }
                            type={
                                batchScanProgress.status === 'RUNNING' ? 'info' :
                                    batchScanProgress.status === 'SUCCESS' ? 'success' :
                                        batchScanProgress.status === 'FAILED' ? 'error' :
                                            batchScanProgress.status === 'CANCELLED' ? 'warning' : 'info'
                            }
                            showIcon
                        />

                        {/* 单元详情列表 */}
                        {batchScanProgress.unitDetails && batchScanProgress.unitDetails.length > 0 && (
                            <div>
                                <h4>单元扫描详情:</h4>
                                <Table
                                    dataSource={batchScanProgress.unitDetails}
                                    columns={[
                                        {
                                            title: '单元ID',
                                            dataIndex: 'unitId',
                                            key: 'unitId',
                                        },
                                        {
                                            title: '状态',
                                            dataIndex: 'status',
                                            key: 'status',
                                            render: (status: string) => {
                                                const colors = {
                                                    PENDING: 'default',
                                                    RUNNING: 'processing',
                                                    SUCCESS: 'success',
                                                    FAILED: 'error'
                                                };
                                                const labels = {
                                                    PENDING: '等待中',
                                                    RUNNING: '运行中',
                                                    SUCCESS: '成功',
                                                    FAILED: '失败'
                                                };
                                                return <Tag color={colors[status as keyof typeof colors] || 'default'}>
                                                    {labels[status as keyof typeof labels] || status}
                                                </Tag>;
                                            }
                                        },
                                        {
                                            title: '开始时间',
                                            dataIndex: 'startTime',
                                            key: 'startTime',
                                            render: (time: string) => time ? new Date(time).toLocaleString() : '-'
                                        },
                                        {
                                            title: '结束时间',
                                            dataIndex: 'endTime',
                                            key: 'endTime',
                                            render: (time: string) => time ? new Date(time).toLocaleString() : '-'
                                        },
                                        {
                                            title: '结果',
                                            dataIndex: 'result',
                                            key: 'result',
                                            render: (result: string) => result ? (
                                                <Tooltip title={result}>
                                                    <span>{result.length > 20 ? result.substring(0, 20) + '...' : result}</span>
                                                </Tooltip>
                                            ) : '-'
                                        }
                                    ]}
                                    pagination={false}
                                    rowKey="unitId"
                                    size="small"
                                    style={{ maxHeight: '300px', overflowY: 'auto' }}
                                />
                            </div>
                        )}
                    </Space>
                )}
            </Modal>
        </div>
    );
};

export default ApplicationDetail;
